package com.shycloud.mido.organ.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.util.UUIDUtil;
import com.shycloud.mido.organ.api.dto.LiveRoomAttachmentDTO;
import com.shycloud.mido.organ.api.dto.LiveRoomInsertDTO;
import com.shycloud.mido.organ.api.entity.LiveRoomAttachment;
import com.shycloud.mido.organ.api.entity.LiveRoomAttachmentImage;
import com.shycloud.mido.organ.api.entity.MemberEntity;
import com.shycloud.mido.organ.api.entity.MiniMessage;
import com.shycloud.mido.organ.api.util.PdfToImageUtil;
import com.shycloud.mido.organ.config.LiveProperties;
import com.shycloud.mido.organ.mapper.LiveMemberEnterMapper;
import com.shycloud.mido.organ.mapper.LiveMemberViewMapper;
import com.shycloud.mido.organ.mapper.LiveRoomAttachmentMapper;
import com.shycloud.mido.organ.mapper.LiveRoomMapper;
import com.shycloud.mido.organ.mapper.MemberMapper;
import com.shycloud.mido.organ.mapper.MessageMapper;
import com.shycloud.mido.organ.mapper.StudentDetailedMapper;
import com.shycloud.mido.organ.service.LiveRoomAttachmentImageService;
import com.shycloud.mido.organ.service.LiveRoomAttachmentService;
import cn.hutool.core.util.URLUtil;
import lombok.AllArgsConstructor;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2021-07-29
 */

@Service
@AllArgsConstructor
public class LiveRoomAttachmentServiceImpl extends ServiceImpl<LiveRoomAttachmentMapper, LiveRoomAttachment> implements LiveRoomAttachmentService {
	
	/** 直播间模块 mapper */
	private LiveRoomMapper liveRoomMapper;
	/** 用户模块 mapper */
	private MemberMapper memberMapper;
	/** 七牛云工具类 */
	private MinioTemplate minioTemplate;
	/** LiveProperties */
	private LiveProperties liveProperties;
	
	private LiveRoomAttachmentImageService liveRoomAttachmentImageService;
	
	private MessageMapper messageMapper;
	
	@Override
	@Async
	@Transactional
	public void addRoom(LiveRoomInsertDTO room) throws Exception {
		String mId= "";
		try {
			if (StringUtils.isBlank(room.getMemberId())) {
				QueryWrapper memberWrapper = new QueryWrapper<>();
				memberWrapper.eq("username", room.getPhone());
				MemberEntity memberEntity = memberMapper.selectOne(memberWrapper);
				if (Objects.isNull(memberEntity)) {
					throw new BusinessException("系统没有此用户");
				}
				String memberId = memberEntity.getId();
				mId = memberId;
				if ("0".equals(memberEntity.getIsTeacher())) {
					throw new BusinessException("学生无法新建直播间");
				}
				//添加房间默认未审核
				room.setStatus("0");
				//0: 用户列表, 1: 机构, 2:运营商
				room.setMemberId(memberId);
				room.setShowAttachment("1");
				room.setCreateTime(LocalDateTime.now());
				liveRoomMapper.insert(room);
			} else {
				MemberEntity memberEntity = memberMapper.selectById(room.getMemberId());
				if (Objects.isNull(memberEntity)) {
					throw new BusinessException("系统没有此用户");
				}
				mId = room.getMemberId();
				if ("0".equals(memberEntity.getIsTeacher())) {
					throw new BusinessException("学生无法新建直播间");
				}
				//添加房间默认未审核
				room.setStatus("0");
				//0: 用户列表, 1: 机构, 2:运营商
				room.setMemberId(room.getMemberId());
				room.setCreateTime(LocalDateTime.now());
				room.setShowAttachment("1");
				liveRoomMapper.insert(room);
			}
			String roomId = room.getId();
			List<LiveRoomAttachmentDTO> attachmentList = room.getAttachmentList();
			if (CollectionUtils.isNotEmpty(attachmentList)) {
				LiveRoomAttachmentDTO liveRoomAttachmentDTO = attachmentList.get(0);

				LiveRoomAttachment liveRoomAttachment = new LiveRoomAttachment();
				liveRoomAttachment.setOssFile(liveRoomAttachmentDTO.getOssFile());
				liveRoomAttachment.setCreateTime(LocalDateTime.now());
				liveRoomAttachment.setLiveroomId(roomId);
				liveRoomAttachment.setIsDisable("0");
				liveRoomAttachment.setName(liveRoomAttachmentDTO.getOssFile()
						.substring(liveRoomAttachmentDTO.getOssFile().lastIndexOf("/") + 1));
				this.save(liveRoomAttachment);


				List<LiveRoomAttachmentImage> imagesList = new ArrayList<>();

				InputStream pdf = URLUtil.getStream(new URL(liveRoomAttachmentDTO.getOssFile()));
				List<byte[]> imageList = PdfToImageUtil.pdfToImage(IOUtils.toByteArray(pdf));
				if (CollectionUtils.isNotEmpty(imageList)) {
					for (int i = 0; i < imageList.size(); i++) {
						byte[] bs = imageList.get(i);
						String url = minioTemplate.uploadFileCdn(new ByteArrayInputStream(bs),
								liveRoomAttachment.getId() + "_" + UUIDUtil.getUUID32(),
								liveProperties.getBucket(), liveProperties.getCdn());
						LiveRoomAttachmentImage liveRoomAttachmentImage =
								new LiveRoomAttachmentImage();
						liveRoomAttachmentImage.setCreateTime(LocalDateTime.now());
						liveRoomAttachmentImage.setIsDisable("0");
						liveRoomAttachmentImage.setLiveroomId(roomId);
						liveRoomAttachmentImage.setAttachmentId(liveRoomAttachment.getId());
						liveRoomAttachmentImage.setName(url.substring(url.lastIndexOf("/") + 1));
						liveRoomAttachmentImage.setSort(i + 1);
						liveRoomAttachmentImage.setOssFile(url);
						imagesList.add(liveRoomAttachmentImage);
					}
					liveRoomAttachmentImageService.saveBatch(imagesList);
				}

			} 
		} catch (Exception e) {
			//消息通知
			MiniMessage miniMessage = new MiniMessage();
			miniMessage.setCreateTime(new Date());
			miniMessage.setMemberId(mId);
			miniMessage.setStatus(0);
			miniMessage.setText(MessageFormatter.arrayFormat("直播间( 名称:{} )审核失败.错误信息：{}",  new String[]{room.getName(),e.getMessage()}).getMessage());
			messageMapper.insert(miniMessage);
		}
	}
}
